package com.school.base.action.admin;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.school.base.model.Admin;
import com.school.base.model.Class;
import com.school.base.model.Course;
import com.school.base.model.Subject;
import com.school.base.service.ClassService;
import com.school.base.service.CourseService;
import com.school.base.service.SubjectService;
import com.school.common.base.BaseAction;
import com.school.common.constant.Constant;
import com.school.common.util.FileUtils;
import com.school.common.util.SpringUtils;
import com.school.common.util.StringUtils;
import com.school.common.util.SystemConfUtils;

/**
 * @author gaobiao
 * 
 */
public class CourseAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7822533066034045738L;
	private static Logger logger = Logger.getLogger(CourseAction.class);
	private static CourseService service = (CourseService) SpringUtils.getBean("base_courseService");
	private Course course;
	private List<Course> courseList;
	private File fileData;
	private String fileDataFileName;

	public File getFileData() {
		return fileData;
	}

	public void setFileData(File fileData) {
		this.fileData = fileData;
	}

	public String getFileDataFileName() {
		return fileDataFileName;
	}

	public void setFileDataFileName(String fileDataFileName) {
		this.fileDataFileName = fileDataFileName;
	}

	public Course getCourse() {
		return course;
	}

	public void setCourse(Course course) {
		this.course = course;
	}

	public List<Course> getCourseList() {
		return courseList;
	}

	public void setCourseList(List<Course> courseList) {
		this.courseList = courseList;
	}

	public String list() {
		courseList = service.getCourseList(course, pageBean);
		return SUCCESS;
	}

	public String edit() {
		if (course != null && course.getId() > 0) {
			course = service.getCourseById(course.getId());
		}
		return SUCCESS;
	}

	public String getClassName(int classId) {
		ClassService classService = (ClassService) SpringUtils.getBean("base_classService");
		Class cls = classService.getClassById(course.getClassId());
		return cls.getName();
	}

	public String editDo() {
		if ("POST".equals(this.getHttpServletRequest().getMethod())) {
			if (course != null) {
				try {
					course.setImgUrl(this.upload());
				} catch (Exception e) {
					this.addActionError(e.getMessage());
					return INPUT;
				}
				if (course.getId() > 0) {
					try {
						service.updateCourse(course);
						logger.info("update Course.");
					} catch (Exception e) {
						this.addActionError(e.getMessage());
						return INPUT;
					}
				} else {
					Admin admin = (Admin) this.getHttpSession().getAttribute(Constant.SESSION_KEY_ADMIN);
					if (admin != null) {
						try {
							service.insertCourse(course, admin.getId());
							logger.info("Insert Course.");
						} catch (Exception e) {
							this.addActionError(e.getMessage());
							return INPUT;
						}
					} else {
						logger.info("Not save course:Admin object is null.");
					}
				}
			} else {
				logger.info("Not save course:course object is null.");
			}
		} else {
			logger.info("Not save course:the request method is not 'post'.");
		}
		return SUCCESS;
	}

	public String delete() {
		if (course != null && course.getId() > 0) {
			try {
				service.deleteCourse(course.getId());
				logger.info("delete course.");
			} catch (Exception e) {
				this.getHttpSession().setAttribute(Constant.ERROR_MESSAGE, e.getMessage());
			}
		} else {
			logger.info("Not delete course:course's id is null.");
		}
		return SUCCESS;
	}

	public List<Subject> getSubjectList() {
		SubjectService subjectService = (SubjectService) SpringUtils.getBean("base_subjectService");
		return subjectService.getAll();
	}

	private String upload() throws Exception {
		if (fileData != null) {
			String ext = fileDataFileName.substring(fileDataFileName.lastIndexOf("."));
			String allowTypes = SystemConfUtils.getProperty("system.fileUpload.image.type");
			if (("," + allowTypes + ",").indexOf("," + ext.substring(1) + ",") == -1) {
				throw new Exception("文件格式不正确，请选择后缀名为(" + allowTypes + ")的文件");
			}
			int maxLength = Integer.parseInt(SystemConfUtils.getProperty("system.fileUpload.image.maxSize"));
			if (fileData.length() > maxLength) {
				throw new Exception("文件过大，请上传小于" + StringUtils.byteUnitTrans(maxLength) + "的文件");
			}
			String filePath = "\\upload\\course\\images\\";
			String imgBaseUrl = SystemConfUtils.getProperty("system.fileUpload.baseUrl");
			String imgDir = this.getServletContext().getRealPath("/") + filePath;
			String fileName = (new Date()).getTime() + ext;
			String fileUrl = imgBaseUrl + filePath.replace("\\", "/") + fileName;
			try {
				FileUtils.saveFile(fileData, imgDir + fileName);
				return fileUrl;
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		return null;
	}

}
